import axios from "axios";
import {Loading} from 'element-ui'
import router from '../router/index';

let loadingInstance = null;
const http = axios.create({
  baseURL: '/api',
  timeout: 3000,
  headers: {
    'Authorization': localStorage.getItem('Authorization') === null ? '' : localStorage.getItem('Authorization'),
    'test': '123'
  },
  crossOrigin: true
});

http.interceptors.request.use(config => {
  loadingInstance = Loading.service({fullscreen: true});
  return config
}, function (error) {
  loadingInstance.close();
  return Promise.reject(error);
});

http.interceptors.response.use(response => {
  // 关闭加载动画
  loadingInstance.close();
  if (response.data.code === 1) {
    router.push('/login');
  }
  return response.data;
}, function (error) {
  loadingInstance.close();
  console.log('data:');
  console.log(error.response.data);
  console.log('status:');
  console.log(error.response.status);
  console.log('message:');
  console.log(error.message);
  console.log('config:');
  console.log(error.config);
  return Promise.reject(error);
});

export default http;
